#include "FileStream.h"
#include "Exception.h"

NS_B2D_BEGIN


FileStream::FileStream(const string& path)
	: mFile(nullptr)
{
	mName = path;
}


FileStream::~FileStream(void)
{
	if(mIsOpen == true)
		close();
}

size_t FileStream::getPosition(void) const
{
	return ftell(mFile);
}

bool FileStream::isEOF(void) const
{
	return feof(mFile) != 0;
}


void FileStream::openImpl(AccessMode mode)
{
	const char* fmode = accessModeTostring(mode);
	mFile = fopen(mName.c_str(), fmode);
	if( mFile != nullptr )
	{
		// Get size
		fseek(mFile,0,SEEK_END);
        mSize = ftell(mFile);
        fseek(mFile,0,SEEK_SET);
	}
	else
	{
		B2D_THROW(Exception::IO_EXCEPTION,
			"Could not open file \""+mName+"\".");
	}
}

void FileStream::closeImpl(void)
{
	fclose(mFile);
	mFile = nullptr;
}

size_t FileStream::seekImpl(size_t offset)
{
	return fseek(mFile, offset, SEEK_SET);
}

size_t FileStream::skipImpl(size_t size)
{
	return fseek(mFile, size, SEEK_CUR);
}

size_t FileStream::readImpl(void* output, size_t size)
{
	return fread(output, 1, size, mFile);
}

size_t FileStream::writeImpl(const void* input, size_t size)
{
	return fwrite(input, 1, size, mFile);
}

const char* FileStream::accessModeTostring(AccessMode mode)
{
	switch(mode)
	{
	case AccessMode::READ: return "rb";
	case AccessMode::WRITE: return "wb";
	default: return "r+b";
	}
}


NS_B2D_END